package com.atguigu.product.service.impl;

import com.atguigu.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.product.dao.CategoryDao;
import com.atguigu.product.entity.CategoryEntity;
import com.atguigu.product.service.CategoryService;


@Service("CategoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> CategoryEntities = baseMapper.selectList(null);
        return CategoryEntities;
    }

    @Override
    public void removeByMenuIds(List<Long> asList) {
        for (Long id : asList) {
            CategoryEntity categoryEntity = baseMapper.selectById(id);
            if (categoryEntity.getCatLevel() == 3){
                baseMapper.deleteById(categoryEntity.getCatId());
            }else if (categoryEntity.getCatLevel() == 2) {
                if (categoryEntity.getChildren().size()==0){
                    baseMapper.deleteById(categoryEntity.getCatId());
                }
            }

        }

    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        path = getcategoryPath(catelogId,path);
        Collections.reverse(path);
        return (Long[]) path.toArray(new Long[path.size()]);
    }

    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotBlank(category.getName())) {
            categoryBrandRelationService.updaCategory(category.getCatId(),category.getName());
        }
    }

    private List<Long> getcategoryPath(Long catelogId,List<Long> path) {
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        path.add(catelogId);
        if (categoryEntity.getParentCid() != 0){
            getcategoryPath(categoryEntity.getParentCid(),path);
        }
        return path;
    }

}